//
//  CTabView.m
//  etionUI
//
//  Created by wangjian on 8/15/13.
//
//

#import "CTabView.h"

#import "UIStyleSkinManagerInternal.h"

#define CTV_MARGIN 5
#define DURATION .3

//-------------------------------------------------------------------------
//  CTabItem

@interface CTabItem ()
{
    NSString *_title;
    UIView *_headView;
}

@end

@implementation CTabItem

@synthesize title = _title;
@synthesize headView = _headView;

- (void)dealloc
{
    [_title release];
    [_headView release];
    [super dealloc];
}

+ (CTabItem *)tabItemWithTitle:(NSString *)title
{
    return [CTabItem tabItemWithTitle:title headView:nil];
}

+ (CTabItem *)tabItemWithTitle:(NSString *)title headView:(UIView *)headView
{
    CTabItem *tabItem = [[[CTabItem alloc] init] autorelease];
    tabItem.title = title;
    tabItem.headView = headView;
    return tabItem;
}

@end

//-------------------------------------------------------------------------
//  CTabItemView

@interface CTabItemView : UIView
{
    UILabel *_titleLable;
}

@property (nonatomic, retain) UILabel *titleLable;
//@property (nonatomic, retain) UIView *headView;

- (void)setWithTitle:(NSString *)title color:(UIColor *)color headViewSize:(CGSize)headViewSize animated:(BOOL)animated;

@end

@implementation CTabItemView

@synthesize titleLable = _titleLable;
//@synthesize headView = _headView;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (UILabel *)titleLable
{
    if (_titleLable == nil)
    {
        _titleLable = [[UILabel alloc] initWithFrame:CGRectZero];
        _titleLable.backgroundColor = [UIColor clearColor];
        _titleLable.font = [UIFont systemFontOfSize:14];
        _titleLable.numberOfLines = 2;
        _titleLable.textAlignment = NSTextAlignmentCenter;
        [self addSubview:_titleLable];
    }
    return _titleLable;
}

- (void)dealloc
{
    [_titleLable release];
    [super dealloc];
}

- (void)setWithTitle:(NSString *)title color:(UIColor *)color headViewSize:(CGSize)headViewSize animated:(BOOL)animated
{
    CGFloat startX = CTV_MARGIN;
    CGFloat titleStartX = CTV_MARGIN;
    CGFloat titleW = 0;
    CGSize titleSize = [title stringSizeWithFont:self.titleLable.font];
    if (headViewSize.width == 0)
    {
        titleW = titleSize.width < self.width-2*CTV_MARGIN ? titleSize.width : self.width-2*CTV_MARGIN;
        titleStartX = startX = (self.width-titleW)/2;
    }
    else
    {
        titleW = titleSize.width < self.width-3*CTV_MARGIN-headViewSize.width ? titleSize.width : self.width-3*CTV_MARGIN-headViewSize.width;
        startX = (self.width-titleW-CTV_MARGIN-headViewSize.width)/2;
        titleStartX = startX + CTV_MARGIN + headViewSize.width;
    }
    
//    CGRect frame = CGRectMake(titleStartX, (self.height-titleSize.height)/2, titleW, titleSize.height);
    CGRect frame = CGRectMake(titleStartX, 0, titleW, self.height);
    self.titleLable.text = title;
    self.titleLable.textColor = color;
    if (animated == NO)
    {
        self.titleLable.frame = frame;
    }
    else
    {
        [UIView animateWithDuration:DURATION animations:^{
            self.titleLable.frame = frame;
        } completion:^(BOOL finished) {
        }];
    }
}

@end

//-------------------------------------------------------------------------
//  CTabContentView

@interface CTabTitlesView : UIView
{
    NSMutableArray *_itemViews;
}

@property (nonatomic, retain) NSMutableArray *itemViews;

@end

@implementation CTabTitlesView

@synthesize itemViews = _itemViews;

- (id)initWithItemSize:(CGSize)itemSize Items:(NSArray *)items titleColor:(UIColor *)titleColor
{
    if (self = [super initWithFrame:CGRectMake(0, 0, itemSize.width*items.count, itemSize.height)])
    {
        self.backgroundColor = [UIColor clearColor];
        self.itemViews = [NSMutableArray arrayWithCapacity:items.count];
        for (NSUInteger i=0; i<items.count; i++)
        {
            CTabItem *item = [items objectAtIndex:i];
            CTabItemView *itemView = [[CTabItemView alloc] initWithFrame:CGRectMake(itemSize.width*i, 0, itemSize.width, itemSize.height)];
            [itemView setWithTitle:item.title color:titleColor headViewSize:item.headView.size animated:NO];
            [self addSubview:itemView];
            [self.itemViews addObject:itemView];
            [itemView release];
        }
    }
    return self;
}

- (void)dealloc
{
    [_itemViews release];
    [super dealloc];
}

@end

@interface CTabTitlesMaskView : UIView
{
    CTabTitlesView *_titlesView;
}

@property(nonatomic, readonly) CTabTitlesView *titlesView;

@end

@implementation CTabTitlesMaskView

@synthesize titlesView = _titlesView;

- (id)initWithItemSize:(CGSize)itemSize Items:(NSArray *)items titleColor:(UIColor *)titleColor
{
    if (self = [super initWithFrame:CGRectMake(0, 0, itemSize.width, itemSize.height)])
    {
        self.backgroundColor = [UIColor clearColor];
        _titlesView = [[CTabTitlesView alloc] initWithItemSize:itemSize Items:items titleColor:titleColor];
        [self addSubview:_titlesView];
        self.clipsToBounds = YES;
    }
    return self;
}

- (void)dealloc
{
    [_titlesView release];
    [super dealloc];
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    _titlesView.frame = CGRectMake(-frame.origin.x, 0, _titlesView.width, _titlesView.height);
}

@end

//-------------------------------------------------------------------------
//  CTabHeadsView

@interface CTabHeadsView : UIView
{
    NSMutableDictionary *_dicHeadViews;
}

- (void)setWithItem:(CTabItem *)item itemSize:(CGSize)itemSize atIndex:(NSUInteger)index animated:(BOOL)animated;

@end

@implementation CTabHeadsView

//@synthesize dicHeadViews = _dicHeadViews;

- (id)initWithItemSize:(CGSize)itemSize Items:(NSArray *)items
{
    self = [super initWithFrame:CGRectMake(0, 0, itemSize.width*items.count, itemSize.height)];
    if (self)
    {
        self.backgroundColor = [UIColor clearColor];
        for (NSUInteger i=0; i<items.count; i++)
        {
            CTabItem *item = [items objectAtIndex:i];
            [self setWithItem:item itemSize:itemSize atIndex:i animated:NO];
        }
    }
    return self;
}

- (NSMutableDictionary *)dicHeadViews
{
    if (_dicHeadViews == nil)
    {
        _dicHeadViews = [[NSMutableDictionary alloc] init];
    }
    return _dicHeadViews;
}

- (void)dealloc
{
    [_dicHeadViews release];
    [super dealloc];
}

- (void)setWithItem:(CTabItem *)item itemSize:(CGSize)itemSize atIndex:(NSUInteger)index animated:(BOOL)animated
{
    CGFloat startX = CTV_MARGIN;
    CGFloat titleW = 0;
    CGSize titleSize = [item.title stringSizeWithFont:[UIFont systemFontOfSize:14]];
    CGRect frame = CGRectZero;
    if (item.headView != nil)
    {
        titleW = titleSize.width < itemSize.width-3*CTV_MARGIN-item.headView.width ? titleSize.width : itemSize.width-3*CTV_MARGIN-item.headView.width;
        startX = (itemSize.width-titleW-CTV_MARGIN-item.headView.width)/2 + index*itemSize.width;
        frame = CGRectMake(startX, (itemSize.height-item.headView.height)/2, item.headView.width, item.headView.height);
    }
    [self setHeadView:item.headView atIndex:index withFrame:frame animated:animated];
}

- (void)setHeadView:(UIView *)headView atIndex:(NSUInteger)index withFrame:(CGRect)frame animated:(BOOL)animated
{
    UIView *oldHeadView = [self.dicHeadViews objectForKey:[NSNumber numberWithUnsignedInteger:index]];
    
    if (animated == NO)
    {
        if (oldHeadView != nil)
        {
            [oldHeadView removeFromSuperview];
            [self.dicHeadViews removeObjectForKey:[NSNumber numberWithUnsignedInteger:index]];
        }
        if (headView != nil)
        {
            headView.frame = frame;
            [self addSubview:headView];
            [self.dicHeadViews setObject:headView forKey:[NSNumber numberWithUnsignedInteger:index]];
        }
    }
    else
    {
        if (oldHeadView == nil && headView != nil)        //add
        {
            headView.frame = CGRectMake(CGRectGetMidX(frame), CGRectGetMidY(frame), 0, 0);
            headView.alpha = 0.0;
            [self addSubview:headView];
            [UIView animateWithDuration:DURATION animations:^{
                headView.frame = frame;
                headView.alpha = 1.0;
            } completion:^(BOOL finished) {
                [self.dicHeadViews setObject:headView forKey:[NSNumber numberWithUnsignedInteger:index]];
            }];
        }
        else if (oldHeadView != nil && headView == nil)   //del
        {
            [UIView animateWithDuration:DURATION animations:^{
                oldHeadView.frame = CGRectMake(CGRectGetMidX(oldHeadView.frame), CGRectGetMidY(oldHeadView.frame), 0, 0);
                oldHeadView.alpha = 0.0;
            } completion:^(BOOL finished) {
                [oldHeadView removeFromSuperview];
                [self.dicHeadViews removeObjectForKey:[NSNumber numberWithUnsignedInteger:index]];
            }];
        }
        else if (oldHeadView != nil && headView != nil)   //replace
        {
            headView.frame = oldHeadView.frame;
            headView.alpha = 0.0;
            [self addSubview:headView];
            [UIView animateWithDuration:DURATION animations:^{
                headView.frame = frame;
                headView.alpha = 1.0;
                oldHeadView.frame = frame;
                oldHeadView.alpha = 0.0;
            } completion:^(BOOL finished) {
                [oldHeadView removeFromSuperview];
                [self.dicHeadViews setObject:headView forKey:[NSNumber numberWithUnsignedInteger:index]];
            }];
        }
    }
}

@end

//-------------------------------------------------------------------------
//  CTabView

@interface CTabView()
{
    UIScrollView *_scrollView;

    CTabTitlesView *_titlesView;
    CTabTitlesMaskView *_maskView;
    CTabHeadsView *_headsView;
    CGSize _itemSize;

    UIColor *_titleColor;
    UIColor *_selectedTitleColor;

    UIImageView *_backgroundView;

    UIImageView *_selectedBackgroundView;

    id<CTabViewDelegate> _delegate;
}

@property (nonatomic, retain) UIScrollView *scrollView;

@property (nonatomic, retain) CTabTitlesView *titlesView;
@property (nonatomic, retain) CTabTitlesMaskView *maskView;
@property (nonatomic, retain) CTabHeadsView *headsView;
@property (nonatomic, assign) CGSize itemSize;

@property (nonatomic, assign) NSUInteger disableIndex;

@end

@implementation CTabView

@synthesize scrollView = _scrollView;

@synthesize curSelectedIndex = _curSelectedIndex;

@synthesize titleColor=_titleColor;
@synthesize selectedTitleColor=_selectedTitleColor;

@synthesize  backgroundView=_backgroundView;
@synthesize  selectedBackgroundView=_selectedBackgroundView;

@synthesize titlesView = _titlesView;
@synthesize maskView = _maskView;
@synthesize headsView = _headsView;
@synthesize itemSize = _itemSize;

@synthesize delegate=_delegate;


- (UIScrollView *)scrollView
{
    if (_scrollView == nil)
    {
        _scrollView = [[UIScrollView alloc] initWithFrame:self.bounds];
        _scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_scrollView];
    }
    return _scrollView;
}

- (UIColor *)titleColor
{
    if (_titleColor == nil)
    {
        _titleColor = [[UIColor colorWithHex:0x494e56] retain];
    }
    return _titleColor;
}

- (UIColor *)selectedTitleColor
{
    if (_selectedTitleColor == nil)
    {
        _selectedTitleColor = [[UIColor whiteColor] retain];
    }
    return _selectedTitleColor;
}

- (UIView *)backgroundView
{
    if (_backgroundView == nil)
    {
        _backgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"tabview_bg"] resizeableCenterImage]];
    }
    return _backgroundView;
}

- (UIView *)selectedBackgroundView
{
    if (_selectedBackgroundView == nil)
    {
        _selectedBackgroundView = [[UIImageView alloc] initWithImage:[[UIImage imageNamed:@"tabview_bg_selected"] resizeableCenterImage]];
    }
    return _selectedBackgroundView;
}

- (NSUInteger)itemNum
{
    return self.titlesView.itemViews.count;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        // Initialization code
        self.backgroundColor = [UIColor whiteColor];
        UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTabView:)];
        [self addGestureRecognizer:tapGesture];
        [tapGesture release];
        
        self.disableIndex = NSUIntegerMax;
        self.scrollView.delegate = self;
        
        if([CUIStyleSkinManager getTabViewStyleSkin]!=nil)
        {
            CTabViewStyleSkin *ss = [CUIStyleSkinManager getTabViewStyleSkin];
            self.selectedTitleColor = ss.selectedTitleColor;
        }
    }
    return self;
}

- (void)dealloc
{
    [_scrollView release_mm];
    
    [_titleColor release_mm];
    [_selectedTitleColor release];
    [_backgroundView release_mm];
    [_selectedBackgroundView release_mm];
    
    [_titlesView release_mm];
    [_maskView release_mm];
    [_headsView release_mm];
    superdealloc_mm;
}

#pragma mark interface

- (CGSize)calculateItemSizeWithItemsNumber:(NSUInteger)number
{
    CGSize size = CGSizeMake(0, self.height);
    if (number <= 3)
    {
        size.width = self.width/(CGFloat)number;
    }
    else
    {
        size.width = self.width/3.5;
    }
    
    return size;
}

- (void)setTabItems:(NSArray *)items
{
    if (items.count == 0)
    {
        return;
    }
    
    self.backgroundView.frame = self.bounds;
    [self insertSubview:self.backgroundView atIndex:0];
    
    self.itemSize = [self calculateItemSizeWithItemsNumber:items.count];
    
    [self.titlesView removeFromSuperview];
    CTabTitlesView *titleView = [[CTabTitlesView alloc] initWithItemSize:self.itemSize Items:items titleColor:self.titleColor];
    self.titlesView = titleView;
    [self.scrollView addSubview:titleView];
    [titleView release];
    
    [self.maskView removeFromSuperview];
    CTabTitlesMaskView *maskView = [[CTabTitlesMaskView alloc] initWithItemSize:self.itemSize Items:items titleColor:self.selectedTitleColor];
    self.maskView = maskView;
    self.selectedBackgroundView.frame = maskView.bounds;
    [maskView insertSubview:self.selectedBackgroundView atIndex:0];
    [self.scrollView addSubview:maskView];
    [maskView release];
    
    [self.headsView removeFromSuperview];
    CTabHeadsView *headsView = [[CTabHeadsView alloc] initWithItemSize:self.itemSize Items:items];
    self.headsView = headsView;
    [self.scrollView addSubview:headsView];
    [headsView release];
    
    self.scrollView.contentSize = CGSizeMake(self.titlesView.width, self.height);
    if (self.titlesView.width <= self.width)
    {
        self.scrollView.scrollEnabled = NO;
    }
}

- (void)setTabItem:(CTabItem *)item atIndex:(NSUInteger)index animated:(BOOL)animated
{
    [self.headsView setWithItem:item itemSize:self.itemSize atIndex:index animated:animated];
    [[self.titlesView.itemViews objectAtIndex:index] setWithTitle:item.title color:self.titleColor headViewSize:item.headView.size animated:YES];
    [[self.maskView.titlesView.itemViews objectAtIndex:index] setWithTitle:item.title color:self.selectedTitleColor headViewSize:item.headView.size animated:YES];
}

- (void)tapTabView:(UITapGestureRecognizer *)tapGesture
{
    CGPoint tapPoint = [tapGesture locationInView:self.scrollView];
    NSUInteger tapIndex = (NSUInteger)(tapPoint.x/self.itemSize.width);
    if (tapIndex < self.disableIndex)
    {
    [self moveToIndex:tapIndex];
}
}

#pragma mark move

- (void)adjustScrollViewWithRect:(CGRect)aimRect animated:(BOOL)aninmated
{
    CGFloat margin = self.itemSize.width/2;
    if (self.scrollView.contentOffset.x>0 && aimRect.origin.x<self.scrollView.contentOffset.x+margin)
    {
        CGFloat startX = CGRectGetMinX(aimRect) - margin;
        [self.scrollView setContentOffset:CGPointMake(startX>0 ? startX : 0, 0) animated:aninmated];
    }
    else if (self.scrollView.contentOffset.x<self.scrollView.contentSize.width-self.scrollView.width
             && CGRectGetMaxX(aimRect)+margin>self.scrollView.contentOffset.x+self.scrollView.width)
    {
        CGFloat startX = CGRectGetMaxX(aimRect)+margin-self.scrollView.width;
        if (startX > self.scrollView.contentSize.width-self.scrollView.width)
        {
            startX = self.scrollView.contentSize.width-self.scrollView.width;
        }
        [self.scrollView setContentOffset:CGPointMake(startX, 0) animated:aninmated];
    }
}

- (void)moveToIndex:(NSUInteger)index   //move inner
{
    if (index == self.curSelectedIndex)
    {
        return;
    }
    [self.delegate tabView:self willSelectItemAtIndex:index];
    _curSelectedIndex = index;
    [self.delegate tabView:self didSelectItemAtIndex:index];
    
    CTabItemView *itemView = [self.titlesView.itemViews objectAtIndex:index];
    [self adjustScrollViewWithRect:itemView.frame animated:YES];
//    [self.scrollView scrollRectToVisible:CGRectMake(index*self.itemSize.width, 0, self.itemSize.width, self.scrollView.height) animated:YES];
    [UIView animateWithDuration:.3 animations:^{
        self.maskView.frame = itemView.frame;
    } completion:^(BOOL finished) {
        
    }];
}

- (void)moveToPositionRate:(CGFloat)rate  //move outside
{
    CGFloat realContentSize = self.scrollView.contentSize.width;
    if (self.disableIndex < self.itemNum)
    {
        realContentSize = self.itemSize.width * self.disableIndex;
    }
    self.maskView.frame = CGRectMake(rate*realContentSize, 0, self.itemSize.width, self.scrollView.height);
    [self adjustScrollViewWithRect:self.maskView.frame animated:NO];
}

- (void)disableItemFromIndex:(NSUInteger)index
{
    self.disableIndex = index;
    for (NSUInteger i=0; i<self.titlesView.itemViews.count; i++)
    {
        CTabItemView *itemView = [self.titlesView.itemViews objectAtIndex:i];
        itemView.titleLable.textColor = i < index ? self.titleColor : [UIColor colorWithHex:0xBDC3C7];
    }
}

@end
